package com.fcl.mylibrary.ImageLoader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;

import com.fcl.mylibrary.R;
import com.fcl.mylibrary.util.FLog;

import java.io.File;
import java.security.MessageDigest;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/3/13.
 */

public class ImageLoader {

    private String TAG = "ImageLoader";
    /**
     * 图片内存缓存
     */
    private LruCache<String, Bitmap> mLruCache;
    /**
     * 后台轮询线程
     */
    private Thread mPoolThread;
    private Handler mPoolThreadHandler;
    /**
     * 线程池
     */
    private ExecutorService mThreadPool;
    private static final int DEAFULT_THREAD_COUNT = 1;
    /**
     * 队列的调度方式
     */
    private Type mType = Type.LIFO;
    /**
     * 任务队列
     */
    private LinkedList<Runnable> mTaskQueue;
    /**
     * UI线程中的Handler
     */
    private Handler mUIHandler;
    private boolean isDiskCacheEnable = true;

    public enum Type{
        FIFO, LIFO
    }

    private static ImageLoader mInstance = new ImageLoader(DEAFULT_THREAD_COUNT, Type.LIFO);

    private ImageLoader(int threadCount, Type type) {
        init(threadCount, type);
    }

    public static ImageLoader getInstance() {
        return mInstance;
    }

    public static ImageLoader getInstance(int threadCount, Type type) {
        if (mInstance == null) {
            synchronized (ImageLoader.class) {
                if (mInstance == null) {
                    mInstance = new ImageLoader(threadCount, type);
                }
            }
        }
        return mInstance;
    }

    private void init(int threadCount, Type type) {
        initBackThread();

        //获取应用最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheMemory = maxMemory/8;
        mLruCache = new LruCache<String, Bitmap>(cacheMemory){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes()*value.getHeight();
            }
        };


        //创建线程池
        mThreadPool = Executors.newFixedThreadPool(threadCount);
        mTaskQueue = new LinkedList<Runnable>();
        mType = type;
    }

    private void initBackThread() {
        FLog.error(TAG, "init back thread");
//        mPoolThreadHandler = new Handler(){
//            @Override
//            public void handleMessage(Message msg) {
//                //线程池取出一个任务执行
//                mThreadPool.execute(getTask());
//            }
//        };
        mPoolThread = new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                mPoolThreadHandler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        //线程池取出一个任务执行
                        mThreadPool.execute(getTask());
                    }
                };
                Looper.loop();
            }
        };
        mPoolThread.start();
    }

    /**
     * 从任务队列取出一个方法
     * @return
     */
    private Runnable getTask() {
        if (mType == Type.FIFO) {
            return mTaskQueue.removeFirst();
        } else if (mType == Type.LIFO) {
            return mTaskQueue.removeLast();
        }
        return null;
    }

    /**
     * 根据path设置图片
     * @param path
     * @param imageView
     * @param isFromNet
     */
    public void loadImage(String path, final ImageView imageView, boolean isFromNet) {
        imageView.setTag(R.string.app_name, path);
        if (mUIHandler == null) {
            mUIHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    //获取bitmap，更新图片
                    ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
                    Bitmap bm = holder.bitmap;
                    ImageView imageview = holder.imageView;
                    String path = holder.path;
                    //将path与tag比较
                    if (imageview.getTag(R.string.app_name).toString().equals(path)) {
                        imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        imageview.setImageBitmap(bm);
                    }
                }
            };
        }

        //根据path在缓存中获取bitamp
        Bitmap bm = getBitmapFromLruCache(path);

        if (bm != null) {
            refreshBitmap(path,imageView,bm);
        } else {
            addTask(buildTask(path,imageView,isFromNet));
        }
    }

    private synchronized void addTask(Runnable runnable) {
        mTaskQueue.add(runnable);
        if (mPoolThreadHandler != null) {
            mPoolThreadHandler.sendEmptyMessage(0x110);
        } else {
            FLog.error(TAG, "pool handler null"+Thread.currentThread().getId());
        }

    }

    /**
     * 根据传入的参数新建任务
     * @param path
     * @param imageView
     * @param isFromNet
     * @return
     */
    private Runnable buildTask(final String path, final ImageView imageView,
                               final boolean isFromNet) {
        return new Runnable() {
            @Override
            public void run() {
                Bitmap bm = null;
                if (isFromNet) {
                    File file = getDiskCacheDir(imageView.getContext(),md5(path));
                    if (file.exists()) { //缓存文件中存在
                        bm = loadImageFromLocal(file.getAbsolutePath(), imageView);
                    } else {
                        if (isDiskCacheEnable) { //是否开启硬盘缓存
                            boolean downloadState = DownloadImageUtil.downloadImgByUrl(path,file);
                            if (downloadState) { //下载成功
                                bm = loadImageFromLocal(file.getAbsolutePath(),imageView);
                            }
                        } else { //直接从网络加载，不缓存
                            bm= DownloadImageUtil.downloadImgByUrl(path,imageView);
                        }
                    }
                } else { //没有网络，从本地加载
                    bm = loadImageFromLocal(path,imageView);
                }
                //图片数据加入内存缓存
                addBitmapToLruCache(path,bm);
                refreshBitmap(path,imageView,bm);
            }
        };
    }

    public String md5(String str) {
        byte[] digest = null;
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            digest = md.digest(str.getBytes());
            return bytes2hex02(digest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String bytes2hex02(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte b : bytes) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() == 1)// 每个字节8为，转为16进制标志，2个16进制位
            {
                tmp = "0" + tmp;
            }
            sb.append(tmp);
        }
        return sb.toString();
    }

    /**
     * 获取缓存图片的地址
     * @param context
     * @param uniqueName
     * @return
     */
    public File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath+File.separator+uniqueName);
    }

    /**
     * 发送更新图片的消息
     * @param path
     * @param imageView
     * @param bm
     */
    private void refreshBitmap(String path, ImageView imageView,
                               Bitmap bm) {
        Message message = Message.obtain();
        ImgBeanHolder holder = new ImgBeanHolder();
        holder.bitmap = bm;
        holder.path=path;
        holder.imageView=imageView;
        message.obj=holder;
        mUIHandler.sendMessage(message);
    }

    /**
     * 从文件中获取bitmap
     * @param path
     * @param imageView
     * @return
     */
    private Bitmap loadImageFromLocal(String path, ImageView imageView) {
        Bitmap bm;
        //获取图片需要显示的大小
        ImageUtil.ImageSize imageSize = ImageUtil.getImageViewSize(imageView);
        bm = decodeSampleeBitmapFromPath(path, imageSize.width,imageSize.height);
        return bm;
    }

    protected Bitmap decodeSampleeBitmapFromPath(String path,int width,
                                                 int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path,options);

        options.inSampleSize = ImageUtil.calculateInSampleSize(options,width,height);

        options.inJustDecodeBounds=false;
        Bitmap bitmap = BitmapFactory.decodeFile(path,options);
        return bitmap;
    }

    /**
     * 从内存缓存获取图片
     * @param key
     * @return
     */
    private Bitmap getBitmapFromLruCache(String key) {
        return mLruCache.get(key);
    }

    /**
     * 将图片加入LruCache
     *
     * @param path
     * @param bm
     */
    protected void addBitmapToLruCache(String path, Bitmap bm)
    {
        if (getBitmapFromLruCache(path) == null)
        {
            if (bm != null)
                mLruCache.put(path, bm);
        }
    }

    private class ImgBeanHolder
    {
        Bitmap bitmap;
        ImageView imageView;
        String path;
    }
}
